/**
 * Admin category jquery
 *
 * date 2015-03-03
 * @author Yongtae Kim
 * @version 1.0.0
 */


/**
 * category treegrid click event
 */
$("table.tree tr").click(function() {
	alert('tree click');

	var btnGroup = '';
	var catDeplmt = 0;
	var depth = 0;

	try {
		//alert(event.type + ": " + $(this).attr("id"));

		// table actived process
		if( !$(this).hasClass("tree-actived") ) {
			// init innerHTML
			btnGroup += '<div class="btn-toolbar">';
			btnGroup += '<div class="btn-group">';
			btnGroup += '<button type="button" id="updateCategory" class="btn btn-default btn-xs"><span class="glyphicon glyphicon-wrench"></span></button>';
			btnGroup += '<button type="button" id="insertCategory" class="btn btn-default btn-xs"><span class="glyphicon glyphicon-plus"></span></button>';
			btnGroup += '<button type="button" id="deleteCategory" class="btn btn-default btn-xs"><span class="glyphicon glyphicon-trash"></span></button>';
			btnGroup += '</div>';
			btnGroup += '</div>';

			// selected clear
			$("table.tree tr").each(function() {
				$(this).removeClass("tree-actived");
				$(this).children().get(1).innerHTML = '';
			});

			// selected add
			$(this).addClass("tree-actived");

			catDeplmt = $("#category_depth_limit").val();
			depth = $("td input[name=depth]", this).val();

			// innerHTML add
			if (depth != 0) {
				$(this).children().get(1).innerHTML = btnGroup;
			}

			// button disable
			if (catDeplmt != 0 && depth != 0 && catDeplmt == depth) {
				depth = $("td button span.glyphicon-wrench", this).parent().attr("disabled", true);
			}

			// category priority ajax
			{
				var categoryCode = $("input[name='category_code']", this).val();
				// ajax
				$.ajax ({
					url: "http://localhost/zswebshop/index.php/admin/category/get_sub_category/" + categoryCode,
					dataType: "json",
					success: display_order_callback,
					error: function(jqXHR, textStatus, errorThrown) {
						var ajaxError = "";
						ajaxError += "ajax error\n";
						ajaxError += "jqXHR: " + jqXHR + "\n";
						ajaxError += "textStatus: " + textStatus + "\n";
						ajaxError += "errorThrown: " + errorThrown;
						alert(ajaxError);
						// console.log(ajaxError);
						throw ajaxError;
					}

				});
			}
		}
	}catch (err) {
		alert(err);
		// console.log(err);
	}
});


/**
 * category treegrid callback function
 *
 * @param json
 * @see $("table.tree tr").click
 */
function display_order_callback(json) {

	var tagStr = "";
	var cnt = 0;

	try {
		// submit button selecter
		var submitBtn = $("#prioritySubmitBtn");

		// button disable
		if (!submitBtn.hasClass("disabled")) {
			submitBtn.addClass("disabled");
		}

		// callback data error check
		if (json.error != null && json.error != '') {
			throw json.error;
		}

		// create tags
		$.each(json.data, function(key, obj) {
			tagStr += '<tr>';
			tagStr += 	'<td>' + obj.category_code + ':' + obj.category_name_pc + '</td>';
			tagStr += 	'<td style="width: 100px;">';
			tagStr += 		'<input type="hidden" name="category_code[]" value="' + obj.category_code + '">';
			tagStr += 		'<input type="text" class="form-control input-sm" name="display_order[]" value="' + obj.display_order + '" maxlength="4" readonly="readonly">';
			tagStr += 	'</td>';
			tagStr += '</tr>';

//			if (cnt == 0) {
//				$("#priority_panel").find("input[name=parent_category_code]").val(obj.parent_category_code);
//			}
			cnt++;
		});

		// set tags
		$("#priority_panel").find("tbody").get(0).innerHTML = "";
		$("#priority_panel").find("tbody").get(0).innerHTML = tagStr;

		// set disabled
		if (cnt > 1) {
			submitBtn.toggleClass("disabled");
			$("#priority_panel").find("input[name='display_order[]']").each(function(){
				$(this).attr("readonly", false);
			});
		}

	} catch (err) {
		alert(err);
		// console.log(err);
	}
}


/**
 * change category priority click event
 */
$('#prioritySubmitBtn').click(function(){
	try {

		// ajax
		$.ajax ({
			url: $('form[name=priorityForm]').attr('action'),
			type: $('form[name=priorityForm]').attr('method'),
			data: $('form[name=priorityForm]').serialize(),
			dataType: "json",
			success: change_priority_callback,
			error: function(jqXHR, textStatus, errorThrown) {
				var ajaxError = "";
				ajaxError += "ajax error\n";
				ajaxError += "jqXHR: " + jqXHR + "\n";
				ajaxError += "textStatus: " + textStatus + "\n";
				ajaxError += "errorThrown: " + errorThrown;
				alert(ajaxError);
				// console.log(ajaxError);
				throw ajaxError;
			}

		});
	} catch(err) {
		alert(err);
		// console.log(err);
	}
});


/**
 * change category priority callback function
 *
 * @param json
 * @see $('#prioritySubmitBtn').click
 */
function change_priority_callback(json) {
	var cnt = 0;
	var errStr = '';
	var tagStr = '';
	var nextURI = '';
	var isDisplayOrderError = false;

	try {
		$.each(json, function(key, obj) {
			if (key == 'error') {

				$.each(obj, function(subKey, subObj) {

					if (subObj != null && subObj != '') {
						errStr += '<p>' + subObj + '</p>';
						if (subKey.indexOf('display_order') != -1) {
							isDisplayOrderError = true;
						}
					}

					cnt++;
				});

				if (errStr.length > 0) {
					tagStr += 	'<label class="control-label" for="inputError">';
					tagStr +=		errStr;
					tagStr += 	'</label>';
				}

				if (tagStr.length > 0) {
					$('#priority_message').get(0).innerHTML = tagStr;
					$('#priority_field').addClass('has-error');
				}
				return false;

			} else if (key == 'data') {
				$.each(obj, function(subKey, subObj) {

					nextURI = subObj;
				});

				alert('순위가 변경되었습니다.');

				location.href = "./category";
				return true;
			} else {
				alert("callback error. [key = " + key + "]");

				return false;
			}

		});

	} catch (err) {
		alert(err);
		// console.log(err);
	}
}



$('#insertCategory').click(function(){
	alert('insertCategory');
	try {
//		alert($(this).parent().innerHTML());
//
//
//		var form = $('#insert_update_panel form[name=insertUpdateForm]');
//
//
//
//
//		form.find('#inputBeforeParentCategoryCode').attr("disabled", false);
//		form.find('#inputParentCategoryCode').attr("disabled", false);
//		form.find('#inputParentCategoryCode').attr("readonly", true);
//		form.find('#inputCategoryCode').attr("disabled", false);
//		form.find('#inputCategoryNamePc').attr("disabled", false);
//		form.find('#insertSubmitBtn').attr("disabled", false);
//		form.find('#updateSubmitBtn').attr("disabled", true);


	} catch (err) {
		alert(err);
	}
});



$('#insertSubmitBtn').click(function(){
	alert('insertSubmitBtn');
	try {

		// ajax
		$.ajax ({
			url: $('form[name=insertUpdateForm]').attr('action') + 'add_category',
			type: $('form[name=insertUpdateForm]').attr('method'),
			data: $('form[name=insertUpdateForm]').serialize(),
			dataType: "json",
			success: add_category_callback,
			error: function(jqXHR, textStatus, errorThrown) {
				var ajaxError = "";
				ajaxError += "ajax error\n";
				ajaxError += "jqXHR: " + jqXHR + "\n";
				ajaxError += "textStatus: " + textStatus + "\n";
				ajaxError += "errorThrown: " + errorThrown;
				alert(ajaxError);
				// console.log(ajaxError);
				throw ajaxError;
			}
		});
	} catch (err) {
		alert(err);
	}
});


function add_category_callback(json) {
	var errStr = '';
	var tagStr = '';
	var cnt = 0;

	//alert(json);

	$.each(json, function(key, obj) {
		if (key == 'error') {
			//alert(key + ':' + obj);
			$.each(obj, function(subKey, subObj) {
				alert(subKey + ':' + subObj);
				if (subObj != null && subObj != '') {
					errStr += '<p>' + subObj + '</p>';
				}

				cnt++;
			});

			if (errStr.length > 0) {
				tagStr += 	'<label class="control-label" for="inputError">';
				tagStr +=		errStr;
				tagStr += 	'</label>';
			}

			if (tagStr.length > 0) {
				$('#insert_update_message').get(0).innerHTML = tagStr;
				//$('#insert_update_field_1').addClass('has-error');
				$('#insert_update_field_2').addClass('has-error');
				$('#insert_update_field_3').addClass('has-error');
			}
			return false;

		} else if (key == 'data') {
			$.each(obj, function(subKey, subObj) {

				nextURI = subObj;
			});

			alert('카테고리 등록 완료!');

			location.href = "./category";
			return true;
		} else {
			alert("callback error. [key = " + key + "]");

			return false;
		}

	});
}


$('#addBtn').click(function(){
	alert('addBtn');

	var isSelected = false;
	var selecter;

	try {
		var form = $('#insert_update_panel form[name=insertUpdateForm]');

		$('table.tree tr').each(function() {
			if ($(this).hasClass('tree-actived')) {
				isSelected = true;
				selecter = $(this);
				return false;	// break
			}
		});

		if (isSelected) {
			// none
			form.find('input').each(function() {
				$(this).attr('disabled', true);
			});
			form.find('select').attr('disabled', true);

			if (!$('#insertSubmitBtn').hasClass('disabled')) {
				$('#insertSubmitBtn').addClass('disabled');
			}
			if (!$('#updateSubmitBtn').hasClass('disabled')) {
				$('#updateSubmitBtn').addClass('disabled');
			}

			// clear
			//$('#inputParentCategoryCode option:eq(0)').attr('selected', true);
			$('#inputParentCategoryCode').val('');
			$('#inputBeforeParentCategoryCode').val('');
			$('#inputCategoryCode').val('');
			$('#inputCategoryNamePc').val('');

			// set
			$('#inputParentCategoryCode').val(selecter.find('input[name=category_code]').val());
			$('#inputBeforeParentCategoryCode').val(selecter.find('input[name=category_code]').val());
			$('#inputCategoryCode').val('');
			$('#inputCategoryNamePc').val('');

			// visible
			form.find('input').each(function() {
				$(this).attr('disabled', false);
			});
			form.find('select').attr('disabled', true);

			$('#insertSubmitBtn').removeClass('disabled');
			if (!$('#updateSubmitBtn').hasClass('disabled')) {
				$('#updateSubmitBtn').addClass('disabled');
			}
		}
	} catch (err) {
		alert(err);
	}
});


$('#modBtn').click(function(){
	alert('modBtn');

	var isSelected = false;
	var selecter;

	try {
		var form = $('#insert_update_panel form[name=insertUpdateForm]');

		$('table.tree tr').each(function() {
			if ($(this).hasClass('tree-actived')) {
				isSelected = true;
				selecter = $(this);
				return false;	// break
			}
		});

		if (isSelected) {
			// none
			form.find('input').each(function() {
				$(this).attr('disabled', true);
			});
			form.find('select').attr('disabled', true);

			if (!$('#insertSubmitBtn').hasClass('disabled')) {
				$('#insertSubmitBtn').addClass('disabled');
			}
			if (!$('#updateSubmitBtn').hasClass('disabled')) {
				$('#updateSubmitBtn').addClass('disabled');
			}

			// clear
			//$('#inputParentCategoryCode option:eq(0)').attr('selected', true);
			$('#inputParentCategoryCode').val('');
			$('#inputBeforeParentCategoryCode').val('');
			$('#inputCategoryCode').val('');
			$('#inputCategoryNamePc').val('');

			// set
			$('#inputParentCategoryCode').val(selecter.find('input[name=parent_category_code]').val());
			$('#inputBeforeParentCategoryCode').val(selecter.find('input[name=parent_category_code]').val());
			$('#inputCategoryCode').val(selecter.find('input[name=category_code]').val());
			$('#inputCategoryNamePc').val(selecter.find('input[name=category_name_pc]').val());

			// visible
			form.find('input').each(function() {
				$(this).attr('disabled', false);
			});
			form.find('select').attr('disabled', false);

			if (!$('#insertSubmitBtn').hasClass('disabled')) {
				$('#insertSubmitBtn').addClass('disabled');
			}
			$('#updateSubmitBtn').removeClass('disabled');
		}
	} catch (err) {
		alert(err);
	}
});


$('#delBtn').click(function(){
	alert('delBtn');

	var isSelected = false;
	var selecter;

	try {
		var form = $('#insert_update_panel form[name=insertUpdateForm]');

		$('table.tree tr').each(function() {
			if ($(this).hasClass('tree-actived')) {
				isSelected = true;
				selecter = $(this);
				return false;	// break
			}
		});


		if (selecter.find('input[name=commodity_count_pc]').val() > 0) {
			alert('category delete is not possible.[commodity_count_pc]');

			return false;
		}


		if (isSelected) {
			// none
			form.find('input').each(function() {
				$(this).attr('disabled', true);
			});
			form.find('select').attr('disabled', true);

			if (!$('#insertSubmitBtn').hasClass('disabled')) {
				$('#insertSubmitBtn').addClass('disabled');
			}
			if (!$('#updateSubmitBtn').hasClass('disabled')) {
				$('#updateSubmitBtn').addClass('disabled');
			}

			// clear
			//$('#inputParentCategoryCode option:eq(0)').attr('selected', true);
			$('#inputParentCategoryCode').val('');
			$('#inputBeforeParentCategoryCode').val('');
			$('#inputCategoryCode').val('');
			$('#inputCategoryNamePc').val('');

			// set
			$('#inputParentCategoryCode').val(selecter.find('input[name=parent_category_code]').val());
			$('#inputBeforeParentCategoryCode').val(selecter.find('input[name=parent_category_code]').val());
			$('#inputCategoryCode').val(selecter.find('input[name=category_code]').val());
			$('#inputCategoryNamePc').val(selecter.find('input[name=category_name_pc]').val());

			// visible
			form.find('input').each(function() {
				$(this).attr('disabled', true);
			});
			form.find('select').attr('disabled', true);

			if (!$('#insertSubmitBtn').hasClass('disabled')) {
				$('#insertSubmitBtn').addClass('disabled');
			}
			if (!$('#updateSubmitBtn').hasClass('disabled')) {
				$('#updateSubmitBtn').addClass('disabled');
			}

			$('#inputCategoryCode').attr('disabled', false);

			return delete_category();
		}
	} catch (err) {
		alert(err);
	}
});


function delete_category() {
	alert('deleteSubmitBtn');
	try {

		// ajax
		$.ajax ({
			url: $('form[name=insertUpdateForm]').attr('action') + 'del_category',
			type: $('form[name=insertUpdateForm]').attr('method'),
			data: $('form[name=insertUpdateForm]').serialize(),
			dataType: "json",
			success: del_category_callback,
			error: function(jqXHR, textStatus, errorThrown) {
				var ajaxError = "";
				ajaxError += "ajax error\n";
				ajaxError += "jqXHR: " + jqXHR + "\n";
				ajaxError += "textStatus: " + textStatus + "\n";
				ajaxError += "errorThrown: " + errorThrown;
				alert(ajaxError);
				// console.log(ajaxError);
				throw ajaxError;
			}
		});
	} catch (err) {
		alert(err);
	}
}


function del_category_callback(json) {
	var errStr = '';
	var tagStr = '';
	var cnt = 0;

	//alert(json);

	$.each(json, function(key, obj) {
		if (key == 'error') {
			//alert(key + ':' + obj);
			$.each(obj, function(subKey, subObj) {
				alert(subKey + ':' + subObj);
				if (subObj != null && subObj != '') {
					errStr += '<p>' + subObj + '</p>';
				}

				cnt++;
			});

			if (errStr.length > 0) {
				tagStr += 	'<label class="control-label" for="inputError">';
				tagStr +=		errStr;
				tagStr += 	'</label>';
			}

			if (tagStr.length > 0) {
				$('#insert_update_message').get(0).innerHTML = tagStr;
				//$('#insert_update_field_1').addClass('has-error');
				$('#insert_update_field_2').addClass('has-error');
				$('#insert_update_field_3').addClass('has-error');
			}
			return false;

		} else if (key == 'data') {
			$.each(obj, function(subKey, subObj) {

				nextURI = subObj;
			});

			alert('카테고리 삭제 완료!');

			location.href = "./category";
			return true;
		} else {
			alert("callback error. [key = " + key + "]");

			return false;
		}

	});
}



/**
 * category screen field reset
 */
function reset_screen() {

}


/**
 * category page ready event
 */
$(document).ready(function() {
	$('.tree').treegrid();

	if (window.location.href.indexOf('change_priority') != -1) {
		var parentCategoryCode = $("#priority_panel").find("input[name=parent_category_code]").val();
		alert('parentCategoryCode = ' + parentCategoryCode);

		$("table.tree tr").each(function() {

			if ($(this).hasClass("treegrid-" + parentCategoryCode)) {
				$(this).click();
			}
		});

	}
});